package com.aijk.web.admin.intercept;

import com.aijk.commons.web.utils.RequestUtils;
import com.aijk.web.admin.Config;
import com.aijk.web.admin.config.WebConfig;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by iscdw on 2016/5/21.
 */
public class BaseInvokeChainStackIntercept implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(BaseInvokeChainStackIntercept.class);

    private List<HandlerInterceptor> interceptors = new ArrayList<>();

    /**
     * 存储请求接收时间键值
     */
    private static final String REQ_ATTR_START = "_startTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("request uri:{} ,params:{}", request.getRequestURI(), JSON.toJSONString(RequestUtils.getQueryParams(request)));

        // 请求开始时间
        long startTime = Clock.systemDefaultZone().millis();
        request.setAttribute(REQ_ATTR_START, startTime);
            for (HandlerInterceptor interceptor : interceptors) {
                if (!interceptor.preHandle(request, response, o)) {
                    return false;
                }
            }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        for (HandlerInterceptor interceptor : interceptors) {
            interceptor.postHandle(request, response, o, modelAndView);
        }
        long startTime = (Long) request.getAttribute(REQ_ATTR_START);
        long endTime = Clock.systemDefaultZone().millis();
        long executeTime = endTime - startTime;
        if(modelAndView != null){
            modelAndView.addObject("image_upload_url", WebConfig.ENV.getValue("image_upload_url"));
            modelAndView.addObject("api_url", WebConfig.ENV.getValue("api_url"));
        }
        logger.info("process time {}", executeTime);

//        modelAndView.addObject("_times", executeTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        for (HandlerInterceptor interceptor : interceptors) {
            interceptor.afterCompletion(request, response, o, e);
        }
    }

    public List<HandlerInterceptor> getInterceptors() {
        return interceptors;
    }

    public void setInterceptors(List<HandlerInterceptor> interceptors) {
        this.interceptors = interceptors;
    }
}
